package my.jieh.tips.web;

import java.util.*;
import java.io.*;

public class STR {
  public static void main(String[] args) throws Exception {
    text2file("This is a test \nof Text.text2file().", "Text.out");
    String text = file2text("Text.out");
    System.out.println(text);
    String xml = "<person name=\"ccc\">ccc@mail.km.kuas.edu.tw<tel>082313530</tel><tel>0938707315</tel></person>";
    System.out.println("xml = "+xml);
    System.out.println("replace(ccc,Chung-Chen Chen) = "+replace(xml, "ccc", "Chung-Chen Chen"));
    System.out.println("expand(xml) = "+expand(xml, "ccc=Chung-Chen Chen"));
    System.out.println("innerText(xml, >, </) = "+innerText(xml, ">", "<"));
    System.out.println("trim(..abc.., .) = "+trim("..abc..", '.'));
  }

  public static String head(String pStr, String pSpliter) {
    int spliterPos = pStr.indexOf(pSpliter);
    if (spliterPos < 0) return pStr;
    return pStr.substring(0,spliterPos);
  }

  public static String tail(String pStr, String pSpliter) {
    int spliterPos = pStr.indexOf(pSpliter);
    if (spliterPos < 0) return "";
    return pStr.substring(spliterPos+pSpliter.length());
  }

  public static String last(String pStr, String pSpliter) {
    int spliterPos = pStr.lastIndexOf(pSpliter);
    if (spliterPos < 0) return pStr;
    return pStr.substring(spliterPos+1);
  }

  public static String noLast(String pStr, String pSpliter) {
    int spliterPos = pStr.lastIndexOf(pSpliter);
    if (spliterPos < 0) return pStr;
    return pStr.substring(0, spliterPos);
  }

  public static byte[] file2bytes(String fileName) throws Exception {
    File f = new File(fileName);
    int length = (int)(f.length());
    FileInputStream fin = new FileInputStream(f);
    DataInputStream in = new DataInputStream(fin);
    byte[] bytes = new byte[length];
    in.readFully(bytes);
    return bytes;
  }

  public static String file2text(String inFile, String pEncode) throws Exception {
    FileInputStream fis = new FileInputStream(inFile);
    InputStreamReader isr = new InputStreamReader(fis);
    if (pEncode != null) isr = new InputStreamReader(fis, pEncode);
    final int  BUFSIZE = 4096;
    BufferedReader reader=new BufferedReader(isr, BUFSIZE);
    StringBuffer rzText = new StringBuffer();
    do {
      char[] buf = new char[BUFSIZE];
      int  len = reader.read(buf, 0, BUFSIZE);
      if (len > 0) {
        String bufStr = new String(buf, 0, len);
        rzText.append(bufStr);
      }
      if (len < BUFSIZE) break;
    } while (true);
    reader.close();
    return replace(rzText.toString(), "\r", "");
  }

  public static String file2text(String inFile) throws Exception {
    return file2text(inFile, null);
  }

  public static void text2file(String pText, String outFile, String pEncode) throws Exception {
    if (outFile.indexOf("\\") > 0) {
      String path = STR.noLast(outFile, "\\");
      File dir = new File(path);
      dir.mkdirs();
    }
    FileOutputStream fos = new FileOutputStream(outFile);
    Writer writer;
    if (pEncode == null)
      writer =new OutputStreamWriter(fos);
    else
      writer = new OutputStreamWriter(fos, pEncode);
    writer.write(replace(pText, "\n", "\r\n"));
    writer.close();
  }

  public static void text2file(String pText, String outFile) throws Exception {
    text2file(pText, outFile, null);
  }

  public static String replace(String pStr, String fromPat, String toPat) {
    if (fromPat.length()==0) return pStr;
    if (pStr.indexOf(fromPat)<0) return pStr;
    StringBuffer rzStr = new StringBuffer();
    int strIdx = 0, nextIdx;
    while ((nextIdx = pStr.indexOf(fromPat, strIdx))>=0) {
      rzStr.append(pStr.substring(strIdx, nextIdx));
      rzStr.append(toPat);
      strIdx = nextIdx + fromPat.length();
    }
    rzStr.append(pStr.substring(strIdx));
    return rzStr.toString();
  }

  public static String innerText(String pXml, String beginMark, String endMark) {
    if (pXml == null) return null;
    int beginStart = pXml.indexOf(beginMark);
    if (beginStart < 0) return null;
    int beginEnd = beginStart+beginMark.length();
    int endStart = pXml.indexOf(endMark, beginEnd);
    if (endStart < 0) return null;
    return pXml.substring(beginEnd, endStart);
  }

  public static String expand(String pText, String pMacros) {
    String[] macros = pMacros.split("\\|");
    for (int i=0; i<macros.length; i++) {
      String name   = head(macros[i], "=");
      String expand = tail(macros[i], "=");
      pText = replace(pText, name, expand);
    }
    return pText;
  }

  public static String trim(String pStr, char pChar) {
    int begin, end;
    for (begin=0; begin<pStr.length(); begin++)
    if (pStr.charAt(begin) != pChar) break;
    for (end = pStr.length()-1; end>0; end--)
    if (pStr.charAt(end) != pChar) break;
    return pStr.substring(begin, end+1);
  }

  public static String format(double d, int decimal) {
    double ratio = Math.pow(10, decimal);
    return ""+Math.round(d*ratio)/ratio;
  }

  public static String tagValue(String pXml, String pTag) {
    String rzValue=innerText(" "+pXml, " "+pTag+"=\"", "\"");
    if (rzValue.length()==0)
      return innerText(" "+pXml, ":"+pTag+"=\"", "\"");
    return rzValue;
  }

  public static TreeMap text2map(String pText) {
    TreeMap map = new TreeMap();
    String[] lines = pText.split("\n");
    for (int i=0; i<lines.length; i++) {
      String[] tokens=lines[i].split("=");
      if (tokens.length >= 2)
        map.put(tokens[0].trim(), tokens[1].trim());
    }
    return map;
  }

  public static String map2text(Map map) {
    StringBuffer rzStr = new StringBuffer();
    Object[] keys = map.keySet().toArray();
    Object[] values = map.values().toArray();
    for (int i=0; i<keys.length; i++)
      rzStr.append(keys[i]+"="+values[i]+"\n");
    return rzStr.toString();
  }
}
